let arr = [3, 5, 6, 4, 9, 1]

for(let i = 0; i < arr.length; i++) {
  for (let j = 0; j< arr.length - 1; j++) {
    if (arr[j] > arr[j+1]) {
      [arr[j], arr[j+1]] = [arr[j+1], arr[j]]
    }
  }
}

let arr = [1, 4, 7, 8, 12, 34, 66, 212, 67787, 324345]

function halfSearch(arr, key) {
  var left = 0
  var right = arr.length - 1
  var mid = Math.floor((left + right) - 2)
  while (left <= arr.length - 1 && right >= 0) {
    if (arr[mid] === key) return mid
    if (left === right) return '不存在'
    if (key < arr[mid]) {
      right = mid - 1
      mid = Math.floor((left + right) - 2)
    } else if (key > arr[mid]) {
      left = mid + 1
      mid = Math.floor((left + right) - 2)
    }

  }
}


var $ = {
  ajax: (option) => {
    let type = option.type || 'get',
        url = option.url,
        data = option.data || '',
        success = option.success,
        error = option.error;
    
    let xhr = new XMLHttpRequest()
    
    if (type === 'post') {
      xhr.open(type, url, true)
      xhr.setRequestHeader('Content-Type', 'application/x-www-from-urlencoded')
    } else {
      xhr.open(type, url + '?' + data, true)
      data = null
    }

    xhr.send(data)

    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          success(xhr.responseText)
        } else {
          error('请求失败')
        }
      }
    }
  }
}


const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'

function MyPromise() {
  var self = this // 保存this
  this.state = PENDING // 初始化状态
  this.value = null // 用于保存 resolve 或者 rejected 传入的值
  this.resolvedCallBacks = [] // 用于保存 resolve 的回调函数
  this.rejectedCallBacks = [] // 用于保存 reject 的回调函数

  function resolve(value) { // 状态转变为 resolved 方法
    // 判断传入元素是否为 Promise 值，如果是，则状态改变必须等待前一个状态改变后再进行改变
    if (value instanceof MyPromise) {
      return value.then(resolve, reject)
    }
    setTimeout(() => {
      if (self.state === PENDING) {
        self.state = RESOLVED
        self.value = value
        self.resolvedCallBacks.forEach(callback => {
          callback(value)
        })
      }
    }, 0)
  }
  function reject(value) {
    setTimeout(() => {
      if (self.state === PENDING) {
        self.state = REJECTED
        self.value = value
        self.rejectedCallBacks.forEach(callback => {
          callback(value)
        })
      }
    }, 0)
  }

  try { // 将两个方法传入函数执行
    fn(resolve, reject)
  } catch (e) { // 遇到错误时，捕获错误，执行 reject 函数
    reject(e)
  }
}
MyPromise.prototype.then = function(onResolved, onRejected) {
  // 首先判断两个参数是否为函数类型
  onResolved = 
    typeof onResolved === 'function'
      ? onResolved
      : function(value) {
        throw value
      };
  onRejected = 
    typeof onRejected === 'function'
    ? onRejected
    : function(error) {
      throw error
    };

  // 如果是等待状态，则将函数加入对应列表中
  if (this.state === PENDING) {
    this.resolvedCallBacks.push(onResolved)
    this.rejectedCallBacks.push(onRejected)
  } 
  // 如果状态已经凝固，则直接执行对应状态的函数
  if (this.state === RESOLVED) {
    onResolved(this.value)
  }
  if (this.state === REJECTED) {
    onRejected(this.value)
  }
}



function promiseAll(promise) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promise)) {
      throw new TypeError('参数有误')
    }
    var resolveCounter = 0
    var promiseNum = promise.length
    var resolveResult = []
    for (let i = 0; i< promiseNum; i++) {
      Promise.resolve(promise[i]).then(value => {
        resolveCounter++
        resolveResult[i] = value
        if (resolveCounter == promiseNum) {
          return resolve(resolveResult)
        }
      }, error => {
        return reject(error)
      })
    }
  })
} 


function debaounce(fn, wait) {
  let timer = null

  return function() {
    let context = this,
      args = arguments;
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    timer = setTimeout(() => {
      fn.apply(context, args)
    }, wait)
  }
}

function throttle(fn, delay) {
  let curTime = Date.now()

  return function() {
    let context = this,
      args = arguments,
      nowTime = Date.now();
    if (nowTime - curTime >= delay) {
      curTime = Date.now()
      return fn.apply(context, args)
    }
  }
}


function deepCopy(object) {
  if (!object || typeof object !== 'object') return
  let newObject = Array.isArray(object) ? []: {}

  for (let key in object) {
    if (object.hasOwnProperty(key)) {
      newObject[key] = 
        typeof object[key] === 'object'? deepCopy(object[key]) : object[key]
    }
  }
  return newObject
}

// 数组扁平化
let arr = [1, [2, [3, 4]]];
function flatten(arr) {
    while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr);
    }
    return arr;
}
console.log(flatten(arr)); //  [1, 2, 3, 4，5]

// 或使用 .flat  arr.flat([depth])
// 其中 depth 是 flat 的参数，depth 是可以传递数组的展开深度（默认不填、数值是 1），即展开一层数组。
// 如果层数不确定，参数可以传进 Infinity，代表不论多少层都要展开
let arr = [1, [2, [3, 4]]];
function flatten(arr) {
  return arr.flat(Infinity);
}
console.log(flatten(arr)); //  [1, 2, 3, 4，5]


let format = n => {
  let num = n.toString()
  let len = num.length
  if (len <= 3) {
      return num
  } else {
      let remainder = len % 3
      if (remainder > 0) { // 不是3的整数倍
          return num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g).join(',') 
      } else { // 是3的整数倍
          return num.slice(0, len).match(/\d{3}/g).join(',') 
      }
  }
}
format(1232323)  // '1,232,323'

